package models

import (
	"gin_vote/dao"
	"time"
)

type User struct {
	Id         int    `db:"id"`
	Username   string `db:"username"`
	Password   string `db:"password"`
	AddTime    int64  `db:"add_time"`
	UpdateTime int64  `db:"update_time"`
}

func (User) TableName() string {
	return "user"
}

func GetUserInfoByUsername(username string) (User, error) {
	var user User
	err := dao.Db.Where("username = ?", username).First(&user).Error
	return user, err
}

func GetUserInfoByUserId(userId int) (User, error) {
	var user User
	err := dao.Db.Where("id = ?", userId).First(&user).Error
	return user, err
}

func AddUser(username string, password string) (int, error) {
	user := User{Username: username, Password: password, AddTime: time.Now().Unix(), UpdateTime: time.Now().Unix()}
	err := dao.Db.Create(&user).Error
	return user.Id, err
}

func UpdateUser(id int) (int64, error) {
	username := "test"
	return dao.Db.Model(&User{}).Where("id = ?", id).Update("username", username).RowsAffected, nil
}

func DeleteUser(userId int) (int64, error) {
	return dao.Db.Where("id = ?", userId).Delete(&User{}).RowsAffected, nil
}
